<?php
namespace app\home\controller;

use app\home\model\IndexModel;
use think\Controller;
use think\Request;
use think\Session;


class Index extends Controller
{
    /**
     * 登录
     */
    public function login(){
        return view('index/login');
    }
    /**
     * 获取token
     */
    public function stati(){
        if (session('access_token') && session('expire_time') > time()) {

            return session('access_token');
        } else {

            $appid = "wx92624d42f765fffa";
            $appsecret = "4594e2d1c7cad29d29fe16e5bc37e669";
            $session_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $appsecret;
            // echo $session_url.'<br/>';
            $res = file_get_contents ( $session_url );
            $ress = json_decode($res);
            $access_token = $ress->access_token;
            //将重新获取到的access_token存到session里
            session('access_token',$access_token);
            echo 1;
            session('expire_time',time() + 3600);
            //echo session('access_token);exit();
            return $access_token;
        }
    }
    public function WeChatprogram($url,$data){
        $datas = json_encode($data);
        $options = array(
            'http' => array(
                'method' => 'post',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' =>$datas,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $res = json_decode($result);
        return $res;
    }

    /**
     * 登录检测
     */
    public function checkLogin(Request $request){
        $map = $request->post();
        if(!$map['name'] && !$map['password']) return 0;
        $data['account'] = $map['name'];
        $data['password'] = $map['password'];
        $result = IndexModel::instance()->checkLogin($data);
        if($result){
            Session::set('bus_bid',$result['bid']);
            Session::set('bus_name',$map['name']);
            $this->success('登录成功', 'commtype/index');
        }else{
            $this->error('账号密码错误');
        }
    }
    /**
     * 退出登录
     */
    public function quitLogin(){
        Session::delete('bus_bid');
        Session::delete('name');
        $this->success('退出成功', 'index/login');
    }

    

    /**
     * 概况分析
     * @param
     */
    public function index(){
        // 跳过登录
        $result = $this->_getBid();
        if(!$result){
            $this->success('未登录', 'index/login');
        }
        $token = $this->stati();
        $url = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailysummarytrend?access_token='.$token;
        $data =  [  'begin_date' =>date("Y-m-d",strtotime("-1 day")),'end_date' =>date("Y-m-d",strtotime("-1 day"))];
        $datas = json_encode($data);
        $options = array(
            'http' => array(
                'method' => 'post',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' =>$datas,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        $res = json_decode($result);
        $this->assign('stitc',$res->list[0]);
        $this->fetch('index/index');
        return view('index/index');
    }
    /*
     * 客服
     */
    public function service(){
        $res = [
            'touser' =>'sdaf' ,
            'msgtype' => 'sadf',
            'text' =>[
                'content' =>"sadf"
            ],
        ];
         $date = json_encode($res);
        $options = array(
            'http' => array(
                'method' => 'post',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' =>$date,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );

        $token =  $this->stati();
        $url =' https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$token;
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
   var_dump($result);
    }

    /*
     * 订单提醒
     */
    public function send()
    {
        $sd = db('goods_order')->where('status > 1')->field('send')->select();
        $remind = 0;
        foreach($sd as $k => $v){
            if($v['send'] === 0){
                $remind = 1;
            }
        }
        if($remind){
            echo json_encode(['res'=> 1]);
        }
        if($remind){
            $sd = db('goods_order')->where('status > 1')->field('send')->update(['send' => 1]);
        }
    }
    public function pwd (){
        $result = $this->_getBid();
        $pwd = input('param.');
        $res = db('business')->where('bid',$result)->field('password')->find();
        if($pwd['date'] != $res['password']){
            echo 0;
        }else{
            echo 1;
        }
    }
    public function regpwd (){
        $result = $this->_getBid();
        $pwd = input('param.');
        $res = db('business')->where('bid',$result)->field('password')->find();
        if($pwd['pwd']){
            db('business')->where('bid',$result)->update(['password' => $pwd['pwd']]);
            Session::delete('bus_bid');
            Session::delete('name');
            $this->success('退出成功', 'index/login');
        }else{
//            echo "<script>alert('新密码不一致')</script>";
        }
    }

    /**
     * 用户分析
     * @param
     */
    public function user(){
        $result = $this->_getBid();
        if(!$result){
            $this->success('未登录', 'index/login');
        }
        //昨日
        $token = $this->stati();
        $url = 'https://api.weixin.qq.com/datacube/getweanalysisappiddailyvisittrend?access_token='.$token;
        $data = [  'begin_date' =>date("Y-m-d",strtotime("-1 day")),'end_date' =>date("Y-m-d",strtotime("-1 day"))];
        $res = $this->WeChatprogram($url,$data);
//        var_dump($res);exit();
        if($ress = db('yestoday')->where('times', $res->list[0]->ref_date)->find()){
            // $this->assign('stitc',$res->list[0]);
            // dump($res) ;
            $this->assign('stitc',$res->list[0]);
            $this->fetch('index/user');
        }else{
            db('yestoday')->insert([
                'times'=>$res->list[0]->ref_date,          //时间
                'yestody'=>$res->list[0]->visit_uv_new,  //新用户
                'opens'=>$res->list[0]->session_cnt,     //打开次数
                'visit_uv'=>$res->list[0]->visit_uv,       //访问人数
                'stay_time_uv'=>$res->list[0]->stay_time_uv,         //停留时间
                'visit_pv'=>$res->list[0]->visit_pv,   //访问次数
            ]);
        }
        $this->assign('stitc',$res->list[0]);
        return view('index/user');
    }

    /**
     * 访问分析
     * @param
     */
    public function visit(){
        return view('home/statistics/visit');
    }

    public function stics(){
       $data =  db('stitc')->limit(5)->field('times,open')->order('id desc')->select();
        echo json_encode(['res'=>$data]);
    }
    public function userStics(){
        $data =  db('yestoday')->limit(5)->field('times,visit_uv')->order('id desc')->select();
        echo json_encode(['res'=>$data]);
    }
}
